package org.example.classloader;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileClassLoader extends ClassLoader {

    private String classDir;

    public FileClassLoader(String classDir) {
        this.classDir = classDir;
    }

    public FileClassLoader(ClassLoader parent, String classDir) {
        super(parent);
        this.classDir = classDir;
    }

    @Override
    protected Class<?> findClass(String className) throws ClassNotFoundException {

        byte[] classData = getClassData(classDir);

        if (null == classData || classData.length == 0) {
            throw new ClassNotFoundException(className);
        }
        return defineClass(className, classData, 0, classData.length);
    }

    public byte[] getClassData(String classDir) {

        try {
            return Files.readAllBytes(Paths.get(classDir));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
